package oylj.recycle.all_in_one.id_card;

import android.content.Context;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.zkteco.android.IDReader.IDPhotoHelper;
import com.zkteco.android.IDReader.WLTService;
import com.zkteco.android.biometric.core.device.ParameterHelper;
import com.zkteco.android.biometric.core.device.TransportType;
import com.zkteco.android.biometric.core.utils.LogHelper;
import com.zkteco.android.biometric.module.idcard.IDCardReader;
import com.zkteco.android.biometric.module.idcard.IDCardReaderFactory;
import com.zkteco.android.biometric.module.idcard.IDCardType;
import com.zkteco.android.biometric.module.idcard.exception.IDCardReaderException;
import com.zkteco.android.biometric.module.idcard.meta.IDCardInfo;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import ZKUSBManager.ZKUSBManager;
import ZKUSBManager.ZKUSBManagerListener;
import oylj.recycle.all_in_one.RecognitionType;

public class IdCardLib {
    private static final String TAG = "IdCardLib";
    private ZKUSBManager zkusbManager = null;
    private IDCardReader idCardReader = null;
    private static final int VID = 1024;    //IDR VID
    private static final int PID = 50010;     //IDR PID
    private CountDownLatch countDownLatch = null;
    private boolean bCancel = false;
    private boolean bStarted = false;

    private Context mContext;
    private Handler submitHandler = null;
    private boolean isInitialized = false;
    public IdCardLib(Context context, Handler handler){
        mContext = context;
        submitHandler = handler;
        zkusbManager = new ZKUSBManager(mContext.getApplicationContext(), zkusbManagerListener);
        zkusbManager.registerUSBPermissionReceiver();
        startService();
    }
    public boolean isInitialized() {
        return isInitialized;
    }


    public void startService(){
        if (!enumSensor()){
            Log.d(TAG, "init: 找不到设备");
            return;
        }
        tryGetUSBPermission();
        isInitialized = true;
    }

    private void tryGetUSBPermission() {
        zkusbManager.initUSBPermission(VID, PID);
    }
    private boolean enumSensor()
    {
        UsbManager usbManager = (UsbManager)mContext.getSystemService(Context.USB_SERVICE);
        for (UsbDevice device : usbManager.getDeviceList().values()) {
            int device_vid = device.getVendorId();
            int device_pid = device.getProductId();
            if (device_vid == VID && device_pid == PID)
            {
                return true;
            }
        }
        return false;
    }

    private ZKUSBManagerListener zkusbManagerListener = new ZKUSBManagerListener() {
        @Override
        public void onCheckPermission(int result) {
            openDevice();
        }

        @Override
        public void onUSBArrived(UsbDevice device) {
            Log.d(TAG, "onUSBArrived: 发现阅读器接入");
        }

        @Override
        public void onUSBRemoved(UsbDevice device) {
            Log.d(TAG, "onUSBRemoved: 阅读器USB被拔出");
        }
    };

    private void openDevice() {
        startIDCardReader();
        try {
            idCardReader.open(0);
            countDownLatch = new CountDownLatch(1);
            new Thread(new Runnable() {
                public void run() {
                    bCancel = false;
                    while (!bCancel) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        boolean ret = false;
                        final long nTickstart = System.currentTimeMillis();
                        try {
                            idCardReader.findCard(0);
                            idCardReader.selectCard(0);
                        }catch (IDCardReaderException e)
                        {
                            continue;
                        }
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        int cardType = 0;
                        try {
                            cardType = idCardReader.readCardEx(0, 0);
                        }
                        catch (IDCardReaderException e)
                        {
                            Log.d(TAG, "run: "+"读卡失败，错误信息：" + e.getMessage());
                            continue;
                        }
                        if (cardType == IDCardType.TYPE_CARD_SFZ || cardType == IDCardType.TYPE_CARD_PRP || cardType == IDCardType.TYPE_CARD_GAT)
                        {
                            final long nTickCommuUsed = (System.currentTimeMillis()-nTickstart);
                            if (cardType == IDCardType.TYPE_CARD_SFZ || cardType == IDCardType.TYPE_CARD_GAT)
                            {
                                IDCardInfo idCardInfo = idCardReader.getLastIDCardInfo();
                                final String name = idCardInfo.getName();
                                final String sex = idCardInfo.getSex();
                                final String nation = idCardInfo.getNation();
                                final String born = idCardInfo.getBirth();
                                final String licid = idCardInfo.getId();
                                final String depart = idCardInfo.getDepart();
                                final String expireDate = idCardInfo.getValidityTime();
                                final String addr = idCardInfo.getAddress();
                                final String passNo = idCardInfo.getPassNum();
                                final int visaTimes = idCardInfo.getVisaTimes();
                                Bitmap bmpPhoto = null;
                                if (idCardInfo.getPhotolength() > 0) {
                                    byte[] buf = new byte[WLTService.imgLength];
                                    if (1 == WLTService.wlt2Bmp(idCardInfo.getPhoto(), buf)) {
                                        bmpPhoto = IDPhotoHelper.Bgr2Bitmap(buf);
                                    }
                                }
                                final int final_cardType = cardType;
                                if (submitHandler != null) {
                                    Message message = submitHandler.obtainMessage(RecognitionType.ID_CARD);
                                    message.obj = licid;  // 字符串
                                    submitHandler.sendMessage(message);
                                }
                            }
                        }
                    }
                    if(countDownLatch!=null){
                        countDownLatch.countDown();
                    }
                }
            }).start();
            bStarted = true;
            Log.d(TAG, "openDevice: "+"打开设备成功，SAMID:" + idCardReader.getSAMID(0));
        } catch (IDCardReaderException e) {
            e.printStackTrace();
            Log.d(TAG, "openDevice: 打开设备失败");
        }

    }

    private void startIDCardReader() {
        if (null != idCardReader)
        {
            IDCardReaderFactory.destroy(idCardReader);
            idCardReader = null;
        }
        // Define output log level
        LogHelper.setLevel(Log.VERBOSE);
        // Start fingerprint sensor
        Map idrparams = new HashMap();
        idrparams.put(ParameterHelper.PARAM_KEY_VID, VID);
        idrparams.put(ParameterHelper.PARAM_KEY_PID, PID);
        idCardReader = IDCardReaderFactory.createIDCardReader(mContext, TransportType.USB, idrparams);
    }

    public void stopService()
    {
        if (bStarted)
        {
            bCancel = true;
            if (null != countDownLatch)
            {
                try {
                    countDownLatch.await(2*1000, TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch = null;
            }
            try {
                idCardReader.close(0);
            } catch (IDCardReaderException e) {
                e.printStackTrace();
            }
            bStarted = false;
        }
    }
}
